<template>
    <el-row>
        <el-col :span="24">
            <Portlet>
              <!--搜索框-->
              <el-form ref="searchForm" class="el-form-col search-form" :model="search">
                <el-row :gutter="15">
                  <el-col :lg="4" :md="6">
                    <el-form-item prop="orderNo" >
                      <el-input v-model="search.orderNo" type="textarea" :rows="4" clearable
                                placeholder="服务订单号  (支持多单查询，用英文逗号分隔)"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :lg="4" :md="6">
                    <el-form-item prop="consigneName" >
                      <el-input clearable placeholder="客户姓名" v-model="search.consigneName"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :lg="4" :md="6">
                    <el-form-item prop="consignePhone" >
                      <el-input clearable placeholder="客户电话" v-model="search.consignePhone"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :lg="4" :md="6">
                    <el-form-item prop="cargoOwner" >
                      <el-input clearable placeholder="商家名称" v-model="search.cargoOwner"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :lg="4" :md="6">
                    <el-form-item>
                      <el-row class="search-btns" :gutter="5">
                        <el-col :span="12">
                          <el-button type="primary" :loading="searchLoading" plain native-type="submit" @click.prevent="searchFunc(search)"><span>搜索</span></el-button>
                        </el-col>
                        <el-col :span="12">
                          <el-button @click="reset('searchForm')" plain>重置</el-button>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </Portlet>
        </el-col>
        <!--<el-col :span="4" :offset="20">-->
          <!--<span><el-button type="info" @click="confirmDialog()"> 批量揽收</el-button></span>-->
        <!--</el-col>-->
        <el-col :span="24">
          <el-card>
            <div slot="header" class="clearfix">
              <span>待揽收列表</span>
              <span class="pull-right">
                  <el-button type="primary" @click="confirmDialog()"> 批量揽收</el-button>
                </span>
            </div>
            <el-row>
              <!--表单-->
              <el-form :model="model" :rules="rules" label-position="left" ref="elForm" label-width="100px">
                <el-form-item label-width="0" prop="chSortingPackageBeans" :rules="[
                  {required: true, message: '商品信息必须', trigger: 'change', type: 'array'}
               ]">
                  <el-table :data="model.chSortingPackageBeans" ref="elTable"
                            v-loading="searchLoading"
                            style="width:100%"
                            border
                            class="text-center"
                            @selection-change="selectionChange"
                  >
                    <el-table-column
                      type="selection"
                      width="55">
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="200px"
                      prop="orderNo"
                      label="订单号"
                    >
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="190px"
                      prop="positionName"
                      label="线路起点"
                    >
                      <template slot-scope="scope">
                        {{ scope.row.startProvince }}{{ scope.row.startCity }}{{ scope.row.startDistrict }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="190px"
                      prop="manufacturersName"
                      label="线路终点"
                    >
                      <template slot-scope="scope">
                        {{ scope.row.endProvince }}{{ scope.row.endCity }}{{ scope.row.endDistrict }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="orderState"
                      label="订单状态">
                      <template slot-scope="scope">
                        {{ scope.row.orderState | filterDataBaseDictionary}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="120px"
                      prop="cargoOwner"
                      label="商家名称">
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="120px"
                      prop="consigneName"
                      label="客户姓名">
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="120px"
                      prop="consignePhone"
                      label="客户电话">
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="150px"
                      label="体积(m³)">
                      <template slot-scope="scope">
                        <el-form-item v-if="scope.row.innerEditing" label-width="0" :prop="'chSortingPackageBeans.' + scope.$index + '.realVolume'" :rules="[
                          {required: true, message: '体积必须', trigger: 'blur'},
                          {validator: isFormatNumber, int: 9, message: '总体积必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                          {validator: range, min: 0.01, message: '总体积必须大于0', trigger: 'blur'}
                       ]">
                          <el-input v-model="scope.row.realVolume" :maxlength="50"></el-input>
                        </el-form-item>
                        <span v-else>{{scope.row.totalVolume}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      min-width="150px"
                      label="重量(kg)">
                      <template slot-scope="scope">
                        <el-form-item v-if="scope.row.innerEditing" label-width="0" :prop="'chSortingPackageBeans.' + scope.$index + '.realWeight'" :rules="[
                          {required: true, message: '重量必须', trigger: 'change'},
                          {validator: isFormatNumber, int: 9,  message: '重量必须是整数小于9位小数小于2位的小数', trigger: 'blur'},
                          {validator: range, min: 0.01,  message: '重量必须大于0', trigger: 'blur'}
                       ]">
                          <el-input v-model="scope.row.realWeight" :min="0" :max="99999" label="重量"></el-input>
                        </el-form-item>
                        <span v-else> {{ scope.row.totalWeight }}</span>
                      </template>
                    </el-table-column>
                    <!--<el-table-column-->
                    <!--align="center"-->
                    <!--min-width="120px"-->
                    <!--prop="productNum"-->
                    <!--label="商品数量">-->
                    <!--</el-table-column>-->
                    <el-table-column
                      prop="totalPackage"
                      align="center"
                      min-width="120px"
                      label="包件数(件)">
                    </el-table-column>
                    <el-table-column
                      prop="money"
                      align="center"
                      min-width="120px"
                      label="费用(元)">
                    </el-table-column>
                    <el-table-column
                      prop="foundTime"
                      min-width="150px"
                      label="下单时间">
                      <template slot-scope="scope">
                        {{ scope.row.foundTime | unixTimestampFilter('YYYY-MM-DD HH:mm')}}
                      </template>
                    </el-table-column>
                    <!--v-if="!scope.row.innerEditing"-->
                    <el-table-column
                      label="操作"
                      width="200"
                    >
                      <template slot-scope="scope">
                        <el-button type="text" class="blue-color" @click="submitForm(scope.row)" v-if="scope.row.innerEditing" :loading="loadingSubmitForm">确认</el-button>
                        <el-button type="text" class="blue-color" @click="changeInnerEditing(scope.row)" v-else>编辑</el-button>
                        <a href="javascript:;" class="blue-color" @click="showDetail(scope.row)" style="margin-left:5px;margin-right:5px;">详情</a>
                        <a href="javascript:;" class="blue-color" @click="confirmDialog(scope.row)">揽收</a>
                      </template>
                    </el-table-column>
                  </el-table>
                  <Pagination style="margin-top: 20px" class="pull-right"
                              :total-item="totalItem"
                              @pagination="pagination"
                              :perItem="params.pageSize" :page.sync="params.pageNum"
                              @sizeChange="sizeChange">
                  </Pagination>
                </el-form-item>
              </el-form>
            </el-row>
          </el-card>
        </el-col>
    </el-row>
</template>
<script>
import {dotData, alert, merge, arrayColumn, confirm} from '@/utils'
import {isFormatNumber, range} from '@/utils/validate'
export default {
  name: 'trunkOrderCollectIndex',
  components: {
  },
  data() {
    return {
      state: 3,
      loading: false,
      searchLoading: false,
      loadingSubmitForm: false,
      rows: [], // 被选中的某些行
      model: { // 把整个表格 都看作是要提交的东东model
        chSortingPackageBeans: [
        ]
      },
      params: {
        pageSize: 20,
        pageNum: 1
      },
      totalItem: 0,
      rules: {},
      search: {
        orderNo: '',
        consigneName: '',
        consignePhone: '',
        cargoOwner: ''
      }
    }
  },
  created() {
    this.getDetail()
  },
  methods: {
    isFormatNumber,
    range,
    showDetail(data) {
      this.$router.push({path: '/ss-oms/orders/service-orders/show/' + data.orderId})
    },
    changeInnerEditing(row) {
      row.innerEditing = true
    },
    // 提交：修改体积 重量
    submitForm(row) {
      this.$refs.elForm.validate(result => {
        if (!result) {
          return
        }
        let data = {}
        data.totalVolume = row.realVolume
        data.totalWeight = row.realWeight
        data.orderId = row.orderId
        this.loadingSubmitForm = true
        this.$ajax.post('/ms-terminal-order/TrunkOrder/editTrunkOrder', data).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$confirm('已完成修改', '提示', {
              type: 'success',
              center: true,
              confirmButtonText: '确定',
              showCancelButton: false,
              closeOnClickModal: false
            }).then(_ => {
              this.$router.push({path: '/redirect/ss-oms/trunkOrder/collect/index'})
            })
          }
        }).finally(_ => {
          this.loadingSubmitForm = false
        })
      })
    },
    selectionChange(rows) {
      this.rows = rows
    },
    searchFunc() {
      this.params = merge(this.params, this.search)
      this.getDetail()
    },
    reset(searchForm) {
      if (this.$refs.searchForm) {
        this.$refs.searchForm.resetFields()
      }
    },
    // 翻页
    pagination(page) {
      this.params.pageNum = page
      this.getDetail()
    },
    // 每页几条
    sizeChange(size) {
      this.params.pageSize = size
      this.getDetail()
    },
    getDetail() {
      this.searchLoading = true
      // this.params.id = '437abfe3-03ed-40d6-ac46-ae1b9f030f79'
      this.$ajax.table('/ms-terminal-order/TrunkOrder/getTrunkOrderList', this.params).then(response => {
        if (response.success) {
          this.totalItem = response.totalItem
          // 获取包件 并初始化 表单model
          this.model.chSortingPackageBeans = response.data || [] // table
          this.model.chSortingPackageBeans.forEach(v => { // 初始化新建字段 放进chSortingPackageBeans里面
            this.$set(v, 'innerEditing', false)
            this.$set(v, 'realVolume', v.totalVolume)
            this.$set(v, 'realWeight', v.totalWeight) // 新建 重量
            this.$set(v, 'orderId', v.orderId) // 新建 订单id
          })
          console.log('0000', this.model.chSortingPackageBeans)
        }
      }).finally(_ => {
        this.searchLoading = false
      })
    },
    // 确认揽收
    confirmDialog(rowData) {
      console.log('rowData', rowData)
      if (rowData && rowData.innerEditing) {
        alert('修改状态下不能进行揽收操作')
      } else {
        let arr = []
        if (rowData === undefined) {
          arr = this.rows
        } else {
          arr = [rowData]
        }
        if (Array.isArray(arr) && arr.length > 0) {
          let innerEditingArr = []
          arr.forEach(v => {
            if (v.innerEditing) {
              innerEditingArr.push(v.innerEditing)
            }
          })
          console.log('innerEditingArr', innerEditingArr)
          if (innerEditingArr.length) {
            alert('修改状态下不能进行揽收操作')
          } else {
            confirm(`
          <p>请确认体积、重量、包件数据正确！</p>
          <p>揽收后信息将提交商家补差。</p>
        `, '揽收确认', {
              confirmButtonLoading: true,
              dangerouslyUseHTMLString: true,
              center: true,
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmCallBack: ({close, confirmButtonLoadingClose}) => {
                this.$ajax.post('/ms-terminal-order/TrunkOrder/trunk-order', {serviceOrderIds: arrayColumn(arr, 'serviceOrderId')}).then(response => {
                  const success = dotData(response, 'success')
                  if (success) {
                    close().then(_ => {
                      confirm(`揽收成功`, undefined, {
                        type: 'success'
                      }).finally(_ => {
                        this.getDetail()
                      })
                      confirmButtonLoadingClose()
                    })
                  } else {
                    confirmButtonLoadingClose()
                  }
                }).catch(_ => {
                  confirmButtonLoadingClose()
                })
              }
            })
          }
        } else {
          alert('请选择数据')
        }
      }
    }
  }
}
</script>
